﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;
using Meraz.Core.Repositories;

namespace Meraz.Core.Commands
{
    public interface ICreateTwitterClientCommand: ICommand<TwitterClient>{
        ITwitterClientRepository Repository { get; set; }
    }
    public class CreateTwitterClientCommand : BaseCommand, ICreateTwitterClientCommand
    {
        public TwitterClient Result{get;set;}
        public ITwitterClientRepository Repository { get; set; }
        public CreateTwitterClientCommand(ITwitterClientRepository repository)
        {
            Repository = repository ?? new TwitterClientRepository();
        }

        public void Execute()
        {
            if (this.Result == null)
                throw new ApplicationException("Illegal state");

            if (string.IsNullOrWhiteSpace(this.Result.Name))
                throw new ApplicationException("Name is missing");

            TwitterClient client = Repository.GetByName(this.Result.Name);
            if (client == null)
            {
                this.Result.ID = 0;//eliminate negative/bogus IDs
                Repository.Add(this.Result);
                Commit();
            }
            else
            {
                Result = client;
            }
        }


    }
}
